package cn.zptc.servlet;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;


import cn.zptc.util.JDBCUtils;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request,HttpServletResponse response)
				throws ServletException, IOException {
		
			response.setContentType("text/html;charset=utf-8");
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			
			
			if ( (find(username)).equals(password)
					) {
				response.sendRedirect("http://www.mafengwo.cn/i/7331468.html");
			
			} else {
				response.sendRedirect("/chapter09/login/index.jsp");
				
			}
		}	
	public void doPost(HttpServletRequest request, 
                           HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	public String find(String username) {
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String password = null;
		
		try {
			// 获得数据的连接
			conn = JDBCUtils.getConnection();
			// 获得Statement对象
			stmt = conn.createStatement();
			// 发送SQL语句
			String sql = "SELECT * FROM users WHERE name = '" + username + "'";
			rs = stmt.executeQuery(sql);
			// 处理结果集
			while (rs.next()) {
				password = rs.getString("password");
				return password;
				}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(rs, stmt, conn);
		}
		return null;
		
	}
}
